<?php

use app\assets\ApiAsset;
use app\assets\LayerAsset;
use app\assets\TableAsset;
use app\assets\MaskedInputAsset;
use app\models\Api;
use app\models\Card;
use app\models\Isp;
use app\models\KeyMap;
use app\models\Package;
use app\widgets\LinkPager;
use app\widgets\ManagerTableOp;
use app\widgets\SortColumnLink;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use dosamigos\datepicker\DatePicker;

/**
 * @var $this yii\web\View
 * @var $usageList app\models\Card[]
 * @var $pagination yii\data\Pagination
 */

ApiAsset::register($this);
LayerAsset::register($this);
TableAsset::register($this);
MaskedInputAsset::register($this);

$this->title = '近期零用量卡列表';
$this->params['breadcrumbs'][] = '物联网卡管理';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php echo Html::beginForm('?', 'get', ['class'=>'form-inline']);?>
<div class="form-group">
    <label for="search_agent" class="sr-only">代理商</label>
    <?php echo Html::textInput('search_agent', Yii::$app->request->get('search_agent'), ['id' => 'search_agent', 'class' => 'form-control', 'placeholder' => '代理商', 'style' => 'width: 120px;']);?>
</div>
<div class="form-group">
    <?php echo Html::checkbox('search_sub_agent', Yii::$app->request->get('search_sub_agent') == 1, ['id' => 'search_sub_agent', 'value' => 1]);?>
    <label for="search_sub_agent">包含下级</label>
</div>
<div class="form-group">
    <label for="search_username" class="sr-only">用户</label>
    <?php echo Html::textInput('search_username', Yii::$app->request->get('search_username'), ['id' => 'search_username', 'class' => 'form-control', 'placeholder' => '用户名', 'style' => 'width: 120px;']);?>
</div>
<div class="form-group">
    <label for="search_status" class="sr-only">状态</label>
    <?php echo Html::dropDownList('search_status', Yii::$app->request->get('search_status'), KeyMap::getValues('card_status'), ['id' => 'search_status', 'class' => 'form-control', 'prompt' => '搜索状态']);?>
</div>
<div class="form-group">
    <label for="search_start_iccid" class="sr-only">ICCID</label>
    <?php echo Html::textInput('search_start_iccid', Yii::$app->request->get('search_start_iccid'), ['id'=>'search_start_iccid', 'class'=>'form-control', 'placeholder'=>'起ICCID', 'style' => 'min-width:180px;']);?>
</div>
<div class="form-group">
    <label for="search_end_iccid" class="sr-only">ICCID</label>
    <?php echo Html::textInput('search_end_iccid', Yii::$app->request->get('search_end_iccid'), ['id'=>'search_end_iccid', 'class'=>'form-control', 'placeholder'=>'止ICCID', 'style' => 'min-width:180px;']);?>
</div>

<div class="form-group">
    <label for="search_msisdn" class="sr-only">MSISDN</label>
    <?php echo Html::textInput('search_msisdn', Yii::$app->request->get('search_msisdn'), ['id'=>'search_msisdn', 'class'=>'form-control', 'placeholder'=>'MSISDN', 'style' => 'width:120px;']);?>
</div>
<div class="form-group">
    <label for="search_batch_no" class="sr-only">批次号</label>
    <?php echo Html::textInput('search_batch_no', Yii::$app->request->get('search_batch_no'), ['id'=>'search_batch_no', 'class'=>'form-control', 'placeholder'=>'批次号']);?>
</div>
<br />
<div class="form-group">
        <label for="search_api_id" class="sr-only">接口</label>
        <?php echo Html::dropDownList('search_api_id', Yii::$app->request->get('search_api_id'), ArrayHelper::map(Api::find()->all(), 'id', 'name'), ['id'=>'search_api_id', 'class'=>'form-control', 'prompt'=>'搜索接口']);?>
    </div>
    <?php if (!empty(Yii::$app->request->get('search_api_id'))) {?>
        <div class="form-group">
            <label for="search_isp_id" class="sr-only">运营商</label>
            <?php echo Html::dropDownList('search_isp_id', Yii::$app->request->get('search_isp_id'), ArrayHelper::map(Isp::find()->andWhere(['status' => Isp::STATUS_OK])->andWhere(['api_id' => Yii::$app->request->get('search_api_id')])->all(), 'id', 'name'), ['id'=>'search_isp_id', 'class'=>'form-control', 'prompt'=>'搜索运营商']);?>
        </div>
    <?php }?>
    <div class="form-group">
        <label for="search_package_id" class="sr-only">套餐</label>
        <?php echo Html::dropDownList('search_package_id', Yii::$app->request->get('search_package_id'), ArrayHelper::map(Package::find()->all(), 'id', 'name'), ['id' => 'search_package_id', 'class' => 'form-control', 'prompt' => '搜索套餐']);?>
    </div>
    <div class="form-group">
        <label for="search_dispatch_time">分配时间:</label>
        <?php echo DatePicker::widget([
            'name' => 'search_dispatch_time',
            'options' => ['placeholder' => ''],
            'attribute' => 'date',
            'template' => '{addon}{input}',
            'value' => Yii::$app->request->get('search_dispatch_time'),
            'clientOptions' => [
                'autoclose' => true,
                'format' => 'yyyy-mm-dd',
                'todayHighlight' => true,
            ]
        ]); ?>
    </div>
    <div class="form-group">
    <label for="generate_time" class="sr-only">Day</label>
    <?php echo Html::textInput('search_start_month', Yii::$app->request->get('search_start_month'), ['id'=>'search_start_month', 'class'=>'form-control masked', 'placeholder'=>'起始月份', 'data-mask'=>'9999-99', 'style'=>'max-width:100px;']);?>
    
    </div>
    <div class="form-group">
    <label for="generate_time" class="sr-only">Day</label>
    <?php echo Html::textInput('search_end_month', Yii::$app->request->get('search_end_month'), ['id'=>'search_end_month', 'class'=>'form-control masked', 'placeholder'=>'结束月份', 'data-mask'=>'9999-99', 'style'=>'max-width:100px;']);?>
    </div>
<div class="form-group">
    <button class="btn btn-primary btn-sm">搜索</button>
    <a href="<?php echo Url::current(['export'=>'excel']);?>">导出Excel</a>
    <a href="<?php echo Url::current(['export'=>'csv']);?>">导出CSV</a>
</div>
<?php echo Html::endForm();?>
<table class="table table-striped table-bordered table-hover">
    <thead>
    <tr>
        <th class="center">
            <label class="pos-rel">
                <input type="checkbox" class="ace" />
                <span class="lbl"><?php echo SortColumnLink::widget(['txt' => '编号', 'name' => 'card.id']);?></span>
            </label>
        </th>
        <th>接口</th>
        <th>运营商</th>
        <th>套餐/<?php echo SortColumnLink::widget(['txt' => '流量用量', 'name' => 'card.data']);?></th>
        <th>当前生效周期</th>
		<th><abbr title="剩余时长"><?php echo SortColumnLink::widget(['txt' => '剩余时长', 'name' => 'card.term_length']);?></abbr>/累计时长</th>
        <th>代理商</th>
        <th>用户</th>
        <th><?php echo SortColumnLink::widget(['txt' => 'ICCID', 'name' => 'card.iccid']);?>/<?php echo SortColumnLink::widget(['txt' => 'MSISDN', 'name' => 'card.msisdn']);?>/IMSI</th>
        <th>状态</th>
        <th>创建/<?php echo SortColumnLink::widget(['txt' => '分配', 'name' => 'card.dispatch_time']);?>/<?php echo SortColumnLink::widget(['txt' => '刷新时间', 'name' => 'card.refresh_time']);?></th>
        <th>操作</th>
    </tr>
    </thead>

    <tbody>
    <?php foreach ($cardList as $usage) {?>
        <tr>
            <td class="center"><label class="pos-rel"><input type="checkbox" class="ace" value="<?php echo $usage->id;?>" /><span class="lbl"><?php echo $usage->id;?></span></label></td>
            <td><?php 
                $api = Api::findOne(['id'=>$usage->card->api_id]);
                echo $api->name;
            ?></td>
            <td><?php
                $isp = Isp::findOne(['id'=>$usage->card->isp_id]);
                echo $isp->name;
            ?></td>
            <td><?php if (empty($usage->card->package_id)) {
                    echo '<i>没有分配</i>';
                } else {
                    echo Html::a(Html::encode($usage->package->name), ['/admin/card/package-view', 'id' => $usage->card->package_id]);
                    echo '（', Yii::$app->formatter->asShortSize($usage->data), '/ ', Yii::$app->formatter->asShortSize($usage->package->data), '）';
                    $dataPercent = $usage->package->data == 0 ? 100 : $usage->data * 100 / $usage->package->data;
                    $smsPercent = $usage->package->sms == 0 ? 100 : $usage->sms * 100 / $usage->package->sms;
                    $voicePercent = $usage->package->voice == 0 ? 100 : $usage->voice * 100 / $usage->package->voice;?>
                    <div class="progress" style="margin-bottom: 3px; height:10px;">
                        <div class="progress-bar progress-bar-<?php echo $dataPercent < 80 ? 'success' : ($dataPercent < 100 ? 'warning' : 'danger');?> progress-bar-striped" role="progressbar" aria-valuenow="<?php echo $usage->data;?>" aria-valuemin="0" aria-valuemax="<?php echo $usage->package->data;?>" style="width: <?php echo $dataPercent;?>%"></div>
                    </div>
                    <div class="progress" style="margin-bottom: 3px; height:10px;">
                        <div class="progress-bar progress-bar-<?php echo $smsPercent < 80 ? 'success' : ($smsPercent < 100 ? 'warning' : 'danger');?> progress-bar-striped" role="progressbar" aria-valuenow="<?php echo $usage->sms;?>" aria-valuemin="0" aria-valuemax="<?php echo $usage->package->sms;?>" style="width: <?php echo $smsPercent;?>%"></div>
                    </div>
                    <div class="progress" style="margin-bottom: 3px; height:10px;">
                        <div class="progress-bar progress-bar-<?php echo $voicePercent < 80 ? 'success' : ($voicePercent < 100 ? 'warning' : 'danger');?> progress-bar-striped" role="progressbar" aria-valuenow="<?php echo $usage->voice;?>" aria-valuemin="0" aria-valuemax="<?php echo $usage->package->voice;?>" style="width: <?php echo $voicePercent;?>%"></div>
                    </div>
                <?php }?></td>
            <td><?php 
                if (!empty($usage->card->active_time)) {
                    //echo $usage->term_length, '(', KeyMap::getValue('card_term_length_unit', $usage->term_length_unit), ')<br />';
					echo Yii::$app->formatter->asDate($usage->card->active_time), ' 激活<br />';
                    if (empty($usage->card->term_start_time)) {
                        echo '----';
                    } else {
                        echo Yii::$app->formatter->asDate($usage->card->term_start_time), ' 起';
                    }
                    echo '<br />';
                    if (empty($usage->card->term_end_time)) {
                        echo '----';
                    } else {
                        //if (time() + 30 * 86400 > $usage->term_end_time) {
                        //    echo '<span class="text-danger" title="30天内到期"><i class="fa fa-exclamation-triangle"></i><strong>', Yii::$app->formatter->asDate($usage->term_end_time), '</strong></span>';
                        //} else {
                            echo Yii::$app->formatter->asDate($usage->card->term_end_time), ' 止';;
                        //}
                    }
                } else {
                    echo '----';
                    echo '<br />';
                    echo '----';
                }?></td>
			    <td><?php 
                if (!empty($usage->card->term_length_unit)) {
					if ( $usage->card->term_length <= 0 ) {
						echo '剩余时长：';
						echo '<span class="text-danger" title="本月底到期"><i class="fa fa-exclamation-triangle"></i><strong>', $usage->card->term_length, '(', KeyMap::getValue('card_term_length_unit', $usage->card->term_length_unit), ')', '</strong></span><br />';
						echo '累计充值：';
						echo $usage->card->order_length, '(', KeyMap::getValue('card_term_length_unit', $usage->card->term_length_unit), ')<br />';
					} else {
						echo '剩余时长：';
						echo $usage->card->term_length, '(', KeyMap::getValue('card_term_length_unit', $usage->card->term_length_unit), ')<br />';
						echo '累计充值：';
						echo $usage->card->order_length, '(', KeyMap::getValue('card_term_length_unit', $usage->card->term_length_unit), ')<br />';
					}
                } else {
                    echo '----';
                    echo '<br />';
                    echo '----';
                }?></td>
            <td><?php if (empty($usage->agent_id)) {?>
                    <i>没有分配</i>
                    <?php if (!empty($usage->package_id)) {?>
                        <br />
                        <a href="<?php echo Url::to(['/admin/card/dispatch', 'iccid_list' => $usage->card->iccid]);?>">分配代理商</a>
                    <?php }
                } else {
                    echo Html::a(Html::encode($usage->agent->username), ['/admin/user/agent-view', 'id' => $usage->agent_id]);?><br />
                    <button class="btn btn-xs" onclick="revokeFromAgent(<?php echo $usage->id;?>)">回收</button>
                <?php }?></td>
            <td><?php if (empty($usage->uid)) {?>
                    <i>没有分配</i>
                    <?php if (!empty($usage->package_id)) {?>
                        <br />
                        <a href="<?php echo Url::to(['/admin/card/dispatch', 'iccid_list' => $usage->card->iccid]);?>">分配用户</a>
                    <?php }
                } else {
                    echo Html::a(Html::encode($usage->user->username), ['/admin/user/user-view', 'id' => $usage->uid]);?><br />
                    <button class="btn btn-xs" onclick="revokeFromUser(<?php echo $usage->card->id;?>)">回收</button>
                <?php }?></td>
            <td><?php echo empty($usage->card->iccid) ? '----' : Html::encode($usage->card->iccid);
                echo '<br />';
                echo empty($usage->card->msisdn) ? '----' : Html::encode($usage->card->msisdn);
                echo '<br />';
                echo empty($usage->card->imsi) ? '----' : Html::encode($usage->card->imsi);?></td>
            <td><?php echo KeyMap::getValue('card_status', $usage->card->status);?><br />
                <?php if ($usage->card->on_off != 1) {
                    echo '未知或离线';
                } else {
                    echo '在线：', $usage->card->ip;
                }?><br />
                <div class="btn-group">
                    <button type="button" class="btn btn-xs btn-info" onclick="refreshCard(<?php echo $usage->card->id;?>, this)" title="刷新状态"><i class="fa fa-refresh"></i></button>
                    <button type="button" class="btn btn-xs btn-warning" onclick="restartCard(<?php echo $usage->id;?>)" title="强制设备断开网络，使其重新注册。"><i class="fa fa-repeat"></i></button>
                    <button type="button" class="btn btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" title="设置状态">
                        <i class="ace-icon fa fa-magic"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <?php foreach (Card::STATUS_TRANSFORM_MAP[$usage->card->status] as $status) {?>
                            <li><a href="javascript:void(0)" onclick="setCardStatus(<?php echo $usage->id, ', ', $status;?>)"><?php echo KeyMap::getValue('card_status', $status);?></a></li>
                        <?php }?>
                    </ul>
                </div>
            </td>
            <td><?php echo Yii::$app->formatter->asDatetime($usage->create_time);
                echo '<br />';
                echo Yii::$app->formatter->asDatetime($usage->card->dispatch_time);
                echo '<br />';
                echo Yii::$app->formatter->asDatetime($usage->card->refresh_time);?></td>
            <td><?php echo ManagerTableOp::widget(['items' => [
                    ['icon' => 'fa fa-info-circle', 'href' => Url::to(['/admin/card/view', 'id' => $usage->id]), 'btn_class' => 'btn btn-xs btn-default', 'tip' => '详情'],
                    ['icon' => 'fa fa-square', 'href' => Url::to(['/admin/card/status-log', 'id' => $usage->id]), 'btn_class' => 'btn btn-xs btn-default', 'tip' => '卡状态'],
                    ['icon' => 'fa fa-pencil', 'href' => Url::to(['/admin/card/edit', 'id' => $usage->id]), 'btn_class' => 'btn btn-xs btn-success', 'tip' => '修改', 'color' => 'green'],
                ]]);?>
            </td>
        </tr>
    <?php }?>
    </tbody>
</table>
<?php echo LinkPager::widget(['pagination' => $pagination]);?>
<style>
    .dropdown-menu {
        min-width:auto;
    }
</style>
<script>
    /**
     * 切换显示高级搜索
     */
    function toggleAdvSearch() {
        if ($('[name=adv_search]').val() != 1) {
            $('.adv_search').removeClass('hide');
            $('[name=adv_search]').val(1);
        } else {
            $('.adv_search').addClass('hide');
            $('[name=adv_search]').val(0);
        }
    }

    /**
     * 刷新卡
     * @param id 卡编号
     * @param btn 当前按钮
     */
    function refreshCard(id, btn) {
        $(btn).prop('disabled', true).find('i').addClass('fa-spin');
        $.getJSON('<?php echo Url::to(['/admin/card/refresh']);?>', {id: id}, function (json) {
            $(btn).prop('disabled', false).find('i').removeClass('fa-spin');
            if (callback(json)) {
                layer.msg('刷新完成。', function () {window.location.reload();});
            }
        });
    }

    /**
     * 强制设备断开网络，使其重新注册。
     */
    function restartCard(id) {
        $.getJSON('<?php echo Url::to(['/admin/card/restart']);?>', {id: id}, function (json) {
            if (callback(json)) {
                layer.msg('已发送强制断开网络命令，请稍等。', function () {});
            }
        });
    }

    /**
     * 设置卡状态
     * @param id 卡编号
     * @param status 设置的状态
     */
    function setCardStatus(id, status) {
        if (!confirm('确定要设置卡状态吗？')) {
            return false;
        }
        $.getJSON('<?php echo Url::to(['/admin/card/set-card-status']);?>', {id: id, status: status}, function (json) {
            if (callback(json)) {
                layer.msg('设置成功，正在刷新。', function () {refreshCard(id, '');});
            }
        });
    }

    /**
     * 回收用户卡
     * @param id 卡编号
     */
    function revokeFromUser(id) {
        if (!confirm('确定要回收此卡吗？')) {
            return false;
        }
        $.getJSON('<?php echo Url::to(['/admin/card/revoke-from-user']);?>', {id: id}, function (json) {
            if (callback(json)) {
                layer.msg('回收完成。', function () {window.location.reload();});
            }
        });
    }

    /**
     * 回收代理商卡
     * @param id 卡编号
     */
    function revokeFromAgent(id) {
        if (!confirm('确定要回收此卡吗？')) {
            return false;
        }
        $.getJSON('<?php echo Url::to(['/admin/card/revoke-from-agent']);?>', {id: id}, function (json) {
            if (callback(json)) {
                layer.msg('回收完成。', function () {window.location.reload();});
            }
        });
    }
</script>
